package com.xiaoqi.lesson.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Author Rookie Coder
 * @Description
 * @Date
 **/
//@WebFilter(value = "/user/*",filterName = "myfilter")
//@Order(1)// 指定该过滤器的顺序
@Slf4j
public class CharsetFilter implements Filter {

    @Value("${open.url}")
    private String openUrl;

    // 过滤所有请求
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        System.out.println("经过过滤器");
        log.info("过滤器地址",requestURI);
        // 1. 判断是否是开放url
        PathMatcher antPathMatcher = new AntPathMatcher();
        if (antPathMatcher.match(openUrl,requestURI)){
            filterChain.doFilter(servletRequest,servletResponse);
        }
        // 2.判断是否携带凭证
        else {
            String token = request.getHeader("token");
            // 判断凭证是否为空
            if (StringUtils.isEmpty(token)){
                request.getRequestDispatcher("/user/open/unLogin").forward(servletRequest,servletResponse);
            }
            else {
                filterChain.doFilter(servletRequest,servletResponse);
            }
        }

    }


}
